﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BitTorrentSharp.BEncoding;
using BitTorrentSharp.Peers;
using BitTorrentSharp.Helpers;

namespace BitTorrentSharp.Tracker
{
    public static class TrackerHelper
    {
        #region consts
        /*
         * Keys
         */
        internal const string PeerIDKey = "peer id";
        internal const string PeerIPKey = "ip";
        internal const string PeerPortKey = "port";

        #endregion

        public static Peer CreatePeerWithNoCompactInput(BDictionary dict)
        {
            if(dict == null)
                throw new ArgumentNullException("dict");

            return new Peer()
            {
                Id = (BString)dict[TrackerHelper.PeerIDKey],
                IP = (BString)dict[TrackerHelper.PeerIPKey],
                Port = (int)(BNumber)dict[TrackerHelper.PeerPortKey]
            };
        }

        /// <summary>
        /// a peer consists six bytes
        /// first fout bytes present IP address
        /// last two bytes present Port
        /// </summary>
        /// <param name="peersContent"></param>
        /// <returns></returns>
        public static Peer[] CreatePeersWithCompactInput(byte[] peersContent)
        {
            if (peersContent == null)
                throw new ArgumentNullException("peersContent");
            if (peersContent.Length % 6 != 0)
                throw new ArgumentException("peersContent's length should be able to divided by 6");
            int count = peersContent.Length / 6;

            Peer[] peers = new Peer[count];

            for (int i = 0; i < count; ++i)
                peers[i] = CreatePeerWithCompactInput(peersContent.Skip(i * 6).Take(6).ToArray());

            return peers;
        }
        /// <summary>
        /// first fout bytes present IP address
        /// last two bytes present Port
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static Peer CreatePeerWithCompactInput(byte[] content)
        {
            if (content == null)
                throw new ArgumentNullException("content");
            if (content.Length != 6)
                throw new ArgumentException("content's Length should be 6");

            Peer peer = new Peer();

            peer.IP = NetworkHelper.ConvertIPv4BytesToString(content.Take(4).ToArray());
            peer.Port = NetworkHelper.ConvertPortBytesToInt(content.Skip(4).Take(2).ToArray());

            return peer;
        }
    }
}
